<template>
  <el-container>
    <el-drawer
      :title="mode == 'add' ? '新增' : mode == 'edit' ? '编辑' : '查看'"
      :wrapperClosable="false"
      :visible.sync="drawer"
      :size="1000"
      :destroy-on-close="true"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <avue-form
            ref="form"
            v-model="form"
            :option="option"
            @submit="submit"
          >
          </avue-form>
        </el-col>
      </el-row>
    </el-drawer>
    <el-drawer
      title="查询构建器"
      :wrapperClosable="false"
      :visible.sync="drawerQuery"
      :size="1000"
      :destroy-on-close="true"
    >
      <el-tabs
        v-model="activeName"
        @tab-click="handleTabsClick"
        style="padding: 0 20px"
      >
        <el-tab-pane label="新建查询" name="first"
          ><avue-form
            :option="queryOption"
            v-model="queryTips"
            @submit="querySubmit"
          >
            <!--<template slot="menuForm">
              <el-button @click="saveTips" icon="el-icon-coin" type="primary"
                >保存查询条件</el-button
              >
            </template>-->
          </avue-form></el-tab-pane
        >
        <!--<el-tab-pane label="已有查询" name="second">配置管理</el-tab-pane>-->
      </el-tabs>
    </el-drawer>
    <el-main>
      <el-card class="box-card">
        <div class="list-search">
          <el-button
            type="primary"
            @click="add"
            icon="el-icon-plus"
            size="small"
            >新增</el-button
          >
          <el-button
            type="primary"
            @click="buildQuery"
            icon="el-icon-notebook-2"
            size="small"
            >高级查询</el-button
          >
          <el-popover
            placement="bottom"
            width="400"
            trigger="click"
            style="margin-left: 10px"
          >
            <el-checkbox-group v-model="ckData">
              <el-checkbox
                v-for="item in diyHeader"
                :key="item.prop"
                :label="item.label"
                :name="item.property"
              ></el-checkbox>
            </el-checkbox-group>
            <el-button
              type="primary"
              icon="el-icon-setting"
              size="small"
              slot="reference"
              @click="diyCloumnFlag = 2"
              >自定义列</el-button
            >
          </el-popover>
          <el-button
            type="primary"
            @click="refresh"
            icon="el-icon-refresh"
            size="small"
            style="margin-left: 10px"
            >刷新</el-button
          >
        </div>
      </el-card>
      <el-card class="box-card" style="margin-top: 10px">
        <el-table
          ref="table"
          :data="tableData"
          style="width: 100%"
          :row-style="{ height: '50px' }"
          :render-header="labelHead"
        >
          <el-table-column
            label="ID"
            prop="id"
            :show-overflow-tooltip="true"
            width="80"
          ></el-table-column>
          <el-table-column
            :label="item.label"
            v-for="item in header"
            :key="item.prop"
            align="center"
          >
            <template slot-scope="scope">{{
              scope.row[item.property]
            }}</template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="200">
            <template #default="scope">
              <el-button
                type="text"
                size="small"
                @click="table_view(scope.row, scope.$index)"
                icon="el-icon-view"
                >查看</el-button
              >
              <el-divider direction="vertical"></el-divider>
              <el-button
                type="text"
                size="small"
                @click="table_edit(scope.row, scope.$index)"
                icon="el-icon-edit"
                >编辑</el-button
              >
              <el-divider direction="vertical"></el-divider>
              <el-popconfirm
                title="确定要删除吗？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="table_del(scope.row, scope.$index)"
              >
                <template #reference>
                  <el-button type="text" size="small" icon="el-icon-delete"
                    >删除</el-button
                  >
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination
            :hide-on-single-page="page.total < page.size ? true : false"
            background
            :current-page="page.currentPage"
            :page-sizes="page.pageSizes"
            :page-size="page.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  data() {
    return {
      activeName: "first",
      diyHeader: [],
      diyCloumnFlag: 1,
      ckData: [],
      mode: "add",
      queryTips: {
        condition: "and",
        childTips: [
          {
            field: "",
            rule: "eq",
            val: "",
          },
        ],
      },
      drawerQuery: false,
      drawer: false,
      form: {},
      option: {},
      nowRowId: 0,
      id: 0,
      header: [],
      search: {
        page: 1,
        limit: 15,
        queryParams: {},
      },
      page: {
        total: 0,
        currentPage: 1,
        size: 15,
        pageSizes: [15, 25, 35, 45],
      },
      tableData: [],
      queryOption: {
        submitText: "查询",
        submitIcon: "el-icon-search",
        labelWidth: 110,
        column: [
          {
            label: "过滤条件匹配",
            prop: "condition",
            type: "select",
            span: 12,
            row: true,
            dicData: [
              {
                label: "AND（所有条件都要求匹配）",
                value: "and",
              },
              {
                label: "OR（条件中的任意一个匹配）",
                value: "or",
              },
            ],
          },
          {
            label: "子表单",
            prop: "childTips",
            type: "dynamic",
            span: 24,
            children: {
              align: "center",
              headerAlign: "center",
              rowAdd: (done) => {
                done({
                  rule: "eq",
                });
              },
              rowDel: (row, done) => {
                done();
              },
              column: [
                {
                  label: "字段",
                  prop: "field",
                  type: "select",
                  dicData: [],
                },
                {
                  label: "条件",
                  prop: "rule",
                  type: "select",
                  dicData: [
                    {
                      label: "等于",
                      value: "eq",
                    },
                    {
                      label: "包含",
                      value: "like",
                    },
                    {
                      label: "以...开始",
                      value: "left_like",
                    },
                    {
                      label: "以...结尾",
                      value: "right_like",
                    },
                    {
                      label: "不等于",
                      value: "neq",
                    },
                    {
                      label: "大于",
                      value: "gt",
                    },
                    {
                      label: "大于等于",
                      value: "gte",
                    },
                    {
                      label: "小于",
                      value: "lt",
                    },
                    {
                      label: "小于等于",
                      value: "lte",
                    },
                  ],
                },
                {
                  label: "值",
                  prop: "val",
                  type: "input",
                },
              ],
            },
          },
        ],
      },
    };
  },
  watch: {
    ckData(newVal, old) {
      if (this.diyCloumnFlag == 2) {
        // 减
        if (newVal.length < old.length) {
          this.header.forEach((ele, index) => {
            if (newVal.indexOf(ele.label) === -1) {
              console.log("被删的", ele.label, index);
              this.header.splice(index, 1);
            }
          });
        } else {
          // 增
          let newHeader = [];
          this.diyHeader.forEach((ele) => {
            if (newVal.indexOf(ele.label) !== -1) {
              newHeader.push(ele);
            }
          });

          this.header = JSON.parse(JSON.stringify(newHeader));
        }
      }
    },
  },
  created() {
    this.id = this.$route.meta.id;
    this.getTableInfo();
  },
  mounted() {},
  methods: {
    labelHead(h, { column, index }) {
      // 动态表头渲染
      return h("span", { class: "table-head", style: { width: "100%" } }, [
        column.label,
      ]);
    },
    // 查询构建器
    async querySubmit(form, done) {
      this.search.queryParams = this.queryTips;
      this.getTableInfo();
      done();
    },
    async getTableInfo() {
      this.search.id = this.id;

      const res = await this.$api.diy.list.get(this.search);
      this.header = JSON.parse(JSON.stringify(res.data.header));
      this.tableData = res.data.data;
      this.page.total = res.data.total;

      res.data.header.forEach((ele) => {
        this.ckData.push(ele.label);
        // 拼装自定义查询的字段部分
        this.queryOption.column[1].children.column[0].dicData.push({
          label: ele.label,
          value: ele.property,
        });
      });

      this.diyHeader = JSON.parse(JSON.stringify(res.data.header));
    },
    async getDiyForm() {
      const res = await this.$api.diy.form.get({ id: this.id });
      this.option = res.data;

      this.option.column.forEach((item) => {
        if (item.type == "upload") {
          if (typeof item.headers == "undefined") {
            item.headers = { authorization: "Bearer " + getToken() };
          } else {
            item.headers.authorization = "Bearer " + getToken();
          }
        }

        if (item.type == "ueditor") {
          item.options.headers = { authorization: "Bearer " + getToken() };
        }
      });

      console.log("更改后", this.option);

      this.option.filterDic = true;

      if (this.mode == "view") {
        this.option.detail = true;
      }
    },
    // 查询tab切换
    handleTabsClick() {
      console.log(this.activeName);
    },
    // 刷新
    refresh() {
      this.search.queryParams = {};
      this.getTableInfo();
    },
    // 保存查询条件
    saveTips() {},
    // 重置查询条件
    resetQuery() {
      this.queryTips = {
        condition: "and",
        childTips: [
          {
            field: "",
            rule: "eq",
            val: "",
          },
        ],
      };
    },
    // 查询构建器
    buildQuery() {
      this.resetQuery();
      this.drawerQuery = true;
      this.queryOption.filterDic = true;
    },
    add() {
      this.mode = "add";
      this.form = {};
      this.getDiyForm();
      this.drawer = true;
    },
    // 提交表单
    async submit() {
      this.form.id = this.id;

      let postData = {};
      for (let key in this.form) {
        if (this.form[key] instanceof Array) {
          // 非子表单
          if (typeof this.form[key][0]["$cellEdit"] == "undefined") {
            postData[key] = this.form[key].join(",");
          } else {
            // 循环子表单转换
            postData[key] = [];
            this.form[key].forEach((ele, index) => {
              postData[key][index] = ele;
              for (let k in ele) {
                if (ele[k] instanceof Array) {
                  postData[key][index][k] = ele[k].join(",");
                } else {
                  postData[key][index][k] = ele[k];
                }
              }
            });
          }
        } else {
          postData[key] = this.form[key];
        }
      }

      let res = {};
      if (this.mode == "add") {
        res = await this.$api.diy.add.post(postData);
      } else {
        postData["pk_id"] = this.nowRowId;
        res = await this.$api.diy.edit.post(postData);
      }

      if (res.code === 0) {
        this.$message.success(res.msg);
        this.drawer = false;
        this.getTableInfo();
      } else {
        this.$message.error(res.msg);
      }
    },
    // 查看
    async table_view(row, index) {
      this.mode = "view";
      this.getDiyForm();
      this.drawer = true;

      this.nowRowId = row.id;
      const res = await this.$api.diy.info.get({
        form_id: this.id,
        table_id: row.id,
      });

      this.form = res.data;
    },
    // 编辑
    async table_edit(row, index) {
      this.mode = "edit";
      this.getDiyForm();
      this.drawer = true;

      this.nowRowId = row.id;
      const res = await this.$api.diy.info.get({
        form_id: this.id,
        table_id: row.id,
      });

      /*let data = [];
      for (let field in res.data) {
        data[field] = JSON.parse(JSON.stringify(res.data[field]));
      }
      console.log(data);*/
      this.form = res.data;
    },
    // 删除
    async table_del(row, index) {
      const res = await this.$api.diy.del.get({
        form_id: this.id,
        table_id: row.id,
      });

      if (res.code === 0) {
        this.$message.success(res.msg);
        this.getTableInfo();
      } else {
        this.$message.error(res.msg);
      }
    },
    // 分页规格改变
    handleSizeChange(val) {
      this.page.size = val;
      this.page.currentPage = 1;
      this.search.page = 1;
      this.search.limit = val;
      this.getList();
    },
    // 分页点击
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.search.page = val;
      this.search.limit = this.page.size;
      this.getList();
    },
  },
};
</script>

<style scoped>
.el-checkbox {
  width: 80px;
}
</style>
